// APP
if (window.plus) {
    earnMoneyPageReady();
} else {
    document.addEventListener('plusready', earnMoneyPageReady, false);
}

// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        earnMoneyPageReady();
    }
});

// 初始化方法
function earnMoneyPageReady() {
    // IScroll
    var _myScroll, _pullUpEl, _pullUpL, _pagecount = 1;
    var _nodata = false, _showend = false;
    var _main = ("fixed" == $(".main").css("position")) ? $(".main") : $(window);
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _contentheight = ($(window).height() - CONFIG_MANAGER.headerHight);

    var earnMoneyPage = function () {
        this.init();
    };
    earnMoneyPage.prototype = {
        // 初始化页面
        init: function () {
            this.initIscroll();
            this.loadData();
            this.bindEvent();
        },

        // 加载数据
        loadData: function () {
            this.loadCategory();
            this.loadgoods(true);
        },

        // 绑定事件
        bindEvent: function () {
            var model = this;
            $("#back").on("click", function () {
                if (AGENT_CLIENT.WEB) {
                    redirect("../home/index.html");
                } else {
                    back();
                }
            });

            // 置顶
            $("#gotop").on("click", function () {
                _myScroll.scrollTo(0, 0, 500);
                $('html,body').animate({scrollTop: '0px'}, 500);
            });

            // 滚动
            _main.scroll(this.isDisplayTopIcon);

            var t1 = null;//这个设置为全局
            // 商品类型
            $("#goodstypetabdiv").on("click", " li", function () {
                var tip = $(this).attr("tip");
                var activeli = $('#goodstypetab li[class=selected]');
                if (activeli.attr("tip") == tip) {
                    return;
                }
                activeli.removeClass("selected");
                $(this).addClass("selected");
                var windowsWidth = $(window).width();
                var pleft = $(this).offset().left;
                if (pleft > (windowsWidth / 2)) {
                    var le = pleft - (windowsWidth * 0.2);
                    $("#goodstypetabdiv").animate({scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'}, 300);
                } else if (pleft < 0) {
                    var le = pleft - (windowsWidth * 0.2);
                    $("#goodstypetabdiv").animate({scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'}, 300);
                }

                model.loadgoods(true);
            });

            // 返现范围
            $("#coinRangelist li").on("click", function () {
                $.showWaiting();
                var tip = $(this).children("a").attr("tip");
                var activeli = $('#coinRangelist a[class=active]');

                activeli.removeClass("active");
                if (activeli.attr("tip") != tip) {
                    $(this).children("a").addClass("active");
                }

                model.loadgoods(true);
            });

            // 跳转商品详情
            $("#goodsitemlist").on("click", "dt[name='goodsimageitem']", function () {
                if (_sharePage.isDisplay) {
                    return;
                }
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });

            // 分享
            $("#goodsitemlist").on("click", "dd[name='shareitem']", function () {
                if (_sharePage.isDisplay) {
                    return;
                }
                //" + item.skuid + "|" + item.sku_name + "|" + item.sku_logo + "share_id"
                var data = $(this).attr("tip").split('|');
                _sharePage.shareInfo = {
                    title: data[1],
                    content: "",
                    href: CONFIG_MANAGER.shareUrl + "goods/goodsdetail.html?id=" + data[0] + "&u=" + _currentloginuser.id + "&s=" + data[3],
                    pic: getImageUrl(data[2], 200, 200),
                    picid: data[2]
                };
                _sharePage.show();
            });
        },

        // 获取分类
        loadCategory: function () {
            var thisPage = this;

            // 读取缓存
            var categorycachedata = getLocalStorage(STORAGE_MANAGER.parentcategory);
            if (categorycachedata) {
                thisPage.paintCategoryPage(categorycachedata);
                return;
            }

            // 获取分类数据
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/basic/category/child/0"
            }).done(function (res) {
                var list = res;
                thisPage.paintCategoryPage(list);
                setLocalStorage(STORAGE_MANAGER.parentcategory, res);
                $("#goodstypetabdiv li:first").addClass("selected");
            });
        },

        // 画页面
        paintCategoryPage: function (list) {
            var html = [];
            html.push(" <li tip='all'>所有分类</li>");
            $.each(list, function (i, item) {
                html.push(" <li tip='" + item.code + "'>" + item.name + "</li>");
            });
            $("#goodstypetab").html(html.join(""));

            // 计算Tab宽度
            var goodstypetabWidth = 0;
            $("#goodstypetab li").each(function () {
                goodstypetabWidth = goodstypetabWidth + ($(this).width() + 19);
            });
            $("#goodstypetab").width(goodstypetabWidth + 10);
        },

        // 获取兑换列表
        loadgoods: function (isreload) {
            var model = this;
            var postdata = {index: _pagecount, size: 16, search: {}};
            // 类型
            var category = $('#goodstypetab li[class=selected]').attr("tip");
            if (category != "all") {
                postdata.search["category"] = category;
            }

            // 价格区间
            var priceRange = $('#coinRangelist a[class=active]').attr("tip");
            if (priceRange != "0") {
                postdata.search["range"] = parseInt(priceRange);
            }

            $.ajax({
                headers: {'Content-Type': 'application/json', token: _currentloginuser.token},
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/share/list/" + _currentloginuser.id,
                data: JSON.stringify(postdata),
                beforeSend: function () {
                    $.showWaiting();
                }
            }).done(function (res) {
                var list = res.data;
                model.paintGoodsItem(list, isreload);
            }).always(function (res) {
                $.closeWaiting();
            }).fail(function (res) {
                var response = JSON.parse(res.responseText);
                if (response.message && response.message.indexOf("票据") > -1) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        redirect("../account/login.html");
                        return;
                    });
                }
            });
        },

        // 画返现商品
        paintGoodsItem: function (list, isreload) {
            if (isreload) {
                _pagecount = 1;
                $("#goodsitemlist").html("");
                $("#pullUp").show();
            }
            if (list.length < 16) {
                $("#pullUp").hide();
            }
            _showend = (list.length == 0);
            if (list.length == 0 && isreload) {
                $("#nodatamessge").show();
            } else {
                $("#nodatamessge").hide();
            }

            var html = [];
            $.each(list, function (i, item) {
                html.push("<li class='syxhd'><dl>");
                html.push("<dt name='goodsimageitem' tip='" + item.skuid + "'><img class='lazy' data-original='" + getImageUrl(item.sku_logo, 350, 350) + "' src='../../images/place/350x350.png'></dt>");
                html.push("<dd>" + item.sku_name + "</dd>");
                html.push("<dd class='jinqian' name='shareitem' tip='" + item.skuid + "|" + item.sku_name + "|" + item.sku_logo + "|" + item.share_id + "'>");
                html.push("<span class='money1'>￥" + item.sku_price + "</span>");
                html.push("<span class='fxstb'><i class='iconfont icon-manjiufantag'></i></span>");
                html.push("<span class='fxs'>" + item.charge_price + "</span>");
                html.push("<span class='yfan'><i class='iconfont icon-fenxiang-yuan'></i></span>");
                html.push("</dd></dl></li>");
            })
            $("#goodsitemlist").append(html.join(""));
            $('img.lazy').lazyload({threshold: 100, failure_limit: 10});
            setTimeout(function () {
                _myScroll.refresh();
            }, 500);
        },

        // 初始化Iscroll
        initIscroll: function () {
            var model = this;
            _pullUpEl = $('#pullUp');
            _pullUpL = _pullUpEl.find('._pullUpLabel');

            _myScroll = new IScroll('#wrapper', {
                probeType: 2,
                scrollbars: true,
                mouseWheel: false,
                fadeScrollbars: true,
                bounce: true,
                interactiveScrollbars: false,
                click: true,
                disableMouse: true,
                disablePointer: true
            })
            ;
            //滚动时
            _myScroll.on('scroll', function () {
            });
            //滚动完毕
            _myScroll.on('scrollEnd', function () {
                if (this.y <= 5 && this.y < (this.maxScrollY + 10)) {
                    if (_nodata || _showend) {
                        return;
                    }
                    pullUpAction();
                }

                $('img.lazy').lazyload({
                    placeholder: "../../images/grey.gif",
                    container: $("#wrapper"),
                    threshold: 100,
                    failure_limit: 10
                });
                model.isDisplayTopIcon(this.y);
            });

            // 上拉显示更多
            function pullUpAction() {
                setTimeout(function () {
                    _pagecount = _pagecount + 1;
                    model.loadgoods(false);
                    _pullUpEl.removeClass('loading');
                    _pullUpL.html('上拉显示更多...');
                    _myScroll.refresh();
                }, 1000);
            }

            document.addEventListener('touchmove', function (e) {
                //e.preventDefault();
            }, false);
        },

        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = (y * -1);
            if (top > _contentheight / 2) {
                $('#gotop').show();
            } else {
                $('#gotop').hide();
            }
        },
    };

    var _earnMoneyPage = new earnMoneyPage();

    // 分享页面
    var _sharePage = new sharePage();

}
